package com.android.tiango.baba.act;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaBaseActivity;
import com.android.tiango.baba.BaBaseApplication;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.entity.OrderModel;
import com.android.tiango.baba.util.Constants;
import com.android.tiango.baba.util.ToastUtils;
import com.android.tiango.baba.util.UploadMoreImageTask;
import com.android.tiango.baba.util.UploadMoreImageTask.UpLoadListener;
import com.android.tiango.baba.view.MeasureGridView;
import com.android.tiango.baba.view.RoundCornerImageView;

/**
 * 晒单
 * 
 * @author suip
 * 
 */

public class ActShareGoods extends BaBaseActivity implements OnClickListener,
		OnRatingBarChangeListener {

	private ImageView mGoodsPicture;
	private RatingBar mRatingBar;
	private EditText mEvaluate;
	private ImageView mShare_picture1;
	private ImageView mShare_picture2;
	private ImageView mShare_picture3;
	private ImageView mShare_picture4;
	private TextView mFenShu;
	private RelativeLayout mRLEvaluate;

	private final int PICTURE1 = 0;
	private final int PICTURE2 = 1;
	private final int PICTURE3 = 2;
	private final int PICTURE4 = 3;
	private OrderModel ordermodel;

	private PopupWindow mPopupWindow;
	private int mPopupWindowWidth;
	private int mPopupWindowHeight;

	private MeasureGridView mGridView;
	private int mWhoCheck = -1;// 判断点击哪个图片进行晒单
	private WindowManager.LayoutParams mWL;
	private boolean isFocus;//弹出输入法判断
	private ImgAdapter mImgAdapter;
	private String picPath1, picPath2, picPath3, picPath4;
	private ArrayList<String> imgList;
	private boolean isFour=false;//是否第四张图片
	private int NoPic=0;//判断哪个是白图片，不能删除它
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_share_goods);

		UploadMoreImageTask task = new UploadMoreImageTask();
		task.setUpLoadListener(new UpLoadListener() {

			@Override
			public void UpLoadResult(ArrayList<String> path) {

			}

			@Override
			public void UpLoadFail() {

			}

			@Override
			public void UpLoadError(ArrayList<String> notUpPath) {

			}
		});
		task.execute(new String[4]);

		initView();
	}

	private void initView() {
		setTitleName("晒单");
		if (null != mTitleBar) {

			mTitleBar.setBackIcon(R.drawable.back);
			setBackOnClickListener();
			mTitleBar.setMoreText("发布");
			mTitleBar.setMoreTextOnClickListener(this);
		}

		mGoodsPicture = (ImageView) findViewById(R.id.goods_picture);
		mRatingBar = (RatingBar) findViewById(R.id.ratingBar1);
		mEvaluate = (EditText) findViewById(R.id.et_evaluate);
		// mShare_picture1 = (ImageView) findViewById(R.id.iv_share_picture1);
		// mShare_picture2 = (ImageView) findViewById(R.id.iv_share_picture2);
		// mShare_picture3 = (ImageView) findViewById(R.id.iv_share_picture3);
		// mShare_picture4 = (ImageView) findViewById(R.id.iv_share_picture4);
		imgList=new ArrayList<String>();
		
		mGridView = (MeasureGridView) findViewById(R.id.measureGridView1);
		mImgAdapter = new ImgAdapter(this, 1);
		mGridView.setAdapter(mImgAdapter);

		mFenShu = (TextView) findViewById(R.id.tv_fenshu);
		mRLEvaluate = (RelativeLayout) findViewById(R.id.rl_evaluate);

		/*mShare_picture1.setOnClickListener(this);
		mShare_picture2.setOnClickListener(this);
		mShare_picture3.setOnClickListener(this);
		mShare_picture4.setOnClickListener(this);*/
		mRatingBar.setOnRatingBarChangeListener(this);
		mRLEvaluate.setOnClickListener(this);
		mWL = getWindow().getAttributes();

		// ordermodel = (OrderModel)
		// getIntent().getExtras().get(Constants.DATA);
		if (null != ordermodel) {
			mGoodsPicture.setImageURI(Uri.fromFile(new File(ordermodel
					.getSimpleProduct().getProductImage().getImageUrl())));
		}
		mWhoCheck=0;
	}

	// 弹出输入法
	void onFocusChange(View v, boolean hasFocus) {
		isFocus = hasFocus;
		(new Handler()).postDelayed(new Runnable() {
			public void run() {
				InputMethodManager imm = (InputMethodManager) mEvaluate
						.getContext().getSystemService(
								Context.INPUT_METHOD_SERVICE);
				if (isFocus) {
					imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
				} else {
					imm.hideSoftInputFromWindow(mEvaluate.getWindowToken(), 0);
				}
			}
		}, 500);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_evaluate:
			mEvaluate.setFocusable(true);
			mEvaluate.setFocusableInTouchMode(true);
			mEvaluate.requestFocus();
			mEvaluate.setHint("");
			onFocusChange(v, true);
			break;
		/*
		 * case R.id.iv_share_picture1: getPopupWindowInstance();
		 * mPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0); mWhoCheck =
		 * PICTURE1; break; case R.id.iv_share_picture2:
		 * getPopupWindowInstance(); mPopupWindow.showAtLocation(v,
		 * Gravity.BOTTOM, 0, 0); mWhoCheck = PICTURE2; break; case
		 * R.id.iv_share_picture3: getPopupWindowInstance();
		 * mPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0); mWhoCheck =
		 * PICTURE3; break; case R.id.iv_share_picture4:
		 * getPopupWindowInstance(); mPopupWindow.showAtLocation(v,
		 * Gravity.BOTTOM, 0, 0); mWhoCheck = PICTURE4; break;
		 */

		case R.id.tv_popup_dismiss:
			getPopupWindowInstance();
			break;

		case R.id.tv_load:
			if (mWhoCheck == PICTURE1) {
				picPath1 = loadPhotos(PICTURE1);
			} else if (mWhoCheck == PICTURE2) {
				picPath2 = loadPhotos(PICTURE2);
			} else if (mWhoCheck == PICTURE3) {
				picPath3 = loadPhotos(PICTURE3);
			} else if (mWhoCheck == PICTURE4) {
				picPath4 = loadPhotos(PICTURE4);
			}

			// showActivity(ActPhotos.class, false);

			break;
		case R.id.tv_photo:
			showActivity(ActPhotoCamera.class, false);
			break;
		case R.id.tv_more:// 点击发布
			loadSubmit();
			break;
		default:
			break;
		}
	}

	class ImgAdapter extends BaseAdapter {

		private int count;
		private Context context;

		public ImgAdapter(Context context, int count) {
			this.count = count;
			this.context = context;
		}

		@Override
		public int getCount() {
			return count;
		}

		public void setMyCount(int i) {
			count = i;
			mImgAdapter.notifyDataSetChanged();
		}
		public int getMyCount() {
			return count;
		}
		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			viewHolder viewholder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(
						R.layout.item_sharegoods_pic, null);
				viewholder = new viewHolder();
				viewholder.img = (ImageView) convertView
						.findViewById(R.id.iv_pic);
				convertView.setTag(viewholder);
			} else {
				viewholder = (viewHolder) convertView.getTag();
			}
			viewholder.img.setTag(position);
			viewholder.img.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					getPopupWindowInstance();
					mPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
					
				}
			});
			
			viewholder.img.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
					// TODO Auto-generated method stub
					int newposition=(Integer) v.getTag();
					
					imgList.remove(newposition);
					if(NoPic==newposition){
						
					}else if(newposition==3){
						isFour=false;
					}else{
						mImgAdapter.setMyCount(mImgAdapter.getCount()-1);
						NoPic-=1;
					}
					
					return false;
				}
			});
			if(position<getCount()-1){
				viewholder.img.setImageURI(Uri.fromFile(new File(imgList.get(position))));
				NoPic=getCount()-1;
			}else{
				viewholder.img.setImageResource(R.drawable.addsharegoods);
			}
			if(isFour&&position==3){
				viewholder.img.setImageURI(Uri.fromFile(new File(imgList.get(position))));
				NoPic=4;
			}
			return convertView;
		}

		class viewHolder {
			private ImageView img;
		}

	}

	// 提交发布
	private void loadSubmit() {
		if (null != ordermodel) {
			String orderId = ordermodel.getOrderId();
			String productId = ordermodel.getSimpleProduct().getProductId();
			String rate = String.valueOf(mRatingBar.getRating());
			String commentContent = mEvaluate.getText().toString().trim();
			// String commentImages=

			HttpParams httpparams = new HttpParams();
			httpparams.put("token", ShareCookie.getToken());// taken
			httpparams.put("orderId", orderId);
			httpparams.put("productId", productId);

			loadSubmit2(httpparams);
		}
	}

	private void loadSubmit2(HttpParams httpparams) {
		HttpClientAsync client = HttpClientAsync.getInstance();

		client.post(HttpUrl.getUrl(HttpUrl.SUBMITCOMMENT), httpparams,
				new HttpCallBack() {
					@Override
					public void onHttpSuccess(Object arg0) {
						ToastUtils.showMessage("成功！！");
					}

					@Override
					public void onHttpStarted() {

					}

					@Override
					public void onHttpFailure(Exception arg0, String arg1) {
						dismissWaitingDialog();

						ToastUtils.showMessage("宝贝获取失败！===" + arg1);

						arg0.printStackTrace();

					}
				});
	}

	// 裁切图片
	private String loadPhotos(int requestCode) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		String name = requestCode + ".jpg";
		name = Environment.getExternalStorageDirectory().getPath()
				+ "/TianGouPicture/" + name;

		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(name)));
		startActivityForResult(intent, requestCode);

		return name;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == Activity.RESULT_OK&&requestCode == PICTURE1) {
			// Bitmap cameraBitmap = (Bitmap) data.getExtras().get("data");
			//mShare_picture1.setImageURI(Uri.fromFile(new File(picPath1)));
			imgList.add(picPath1);
			// mShare_picture1.setImageBitmap(cameraBitmap);
			//mShare_picture2.setVisibility(View.VISIBLE);
			mImgAdapter.setMyCount(mImgAdapter.getCount()+1);
			getPopupWindowInstance();
			mWhoCheck = PICTURE2;
		} else if (requestCode == PICTURE2 &&
				 resultCode == Activity.RESULT_OK) {
			// Bitmap cameraBitmap = (Bitmap) data.getExtras().get("data");
			imgList.add(picPath2);
			mImgAdapter.setMyCount(mImgAdapter.getCount()+1);
			mWhoCheck = PICTURE3;
			getPopupWindowInstance();
		} else if (requestCode == PICTURE3 && data != null
				&& resultCode == Activity.RESULT_OK) {
			// Bitmap cameraBitmap = (Bitmap) data.getExtras().get("data");
			imgList.add(picPath3);
			mImgAdapter.setMyCount(mImgAdapter.getCount()+1);
			mWhoCheck = PICTURE4;
			getPopupWindowInstance();
		} else if (requestCode == PICTURE4 && data != null
				&& resultCode == Activity.RESULT_OK) {
			// Bitmap cameraBitmap = (Bitmap) data.getExtras().get("data");
			imgList.add(picPath4);
			isFour=true;
			mImgAdapter.setMyCount(mImgAdapter.getCount());
			getPopupWindowInstance();
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onRatingChanged(RatingBar ratingBar, float rating,
			boolean fromUser) {

		mFenShu.setText("" + (int) rating + "分");
	}

	/*
	 * PopupWindow
	 */
	private void getPopupWindowInstance() {
		if (null != mPopupWindow) {
			mPopupWindow.dismiss();
			mPopupWindow = null;
			mWL.alpha = 1;
			getWindow().setAttributes(mWL);
			return;
		} else {
			mWL.alpha = 0.5f; // 0.0-1.0
			getWindow().setAttributes(mWL);
			initPopuptWindow();
		}
	}

	/*
	 * PopupWindow
	 */
	private void initPopuptWindow() {
		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.popup_window, null);

		mPopupWindow = new PopupWindow(popupWindow,
				BaBaseApplication.mWidth - 80, 600);
		mPopupWindow.setFocusable(true);

		mPopupWindowWidth = mPopupWindow.getWidth();
		mPopupWindowHeight = mPopupWindow.getHeight();

		// mPopupWindow.setWindowLayoutMode((mScreenWidth-mPopupWindowWidth)/2,
		// mScreenHeight-mPopupWindowHeight);
		TextView popup_dismiss = (TextView) popupWindow
				.findViewById(R.id.tv_popup_dismiss);
		TextView popup_load = (TextView) popupWindow.findViewById(R.id.tv_load);
		TextView popup_camera = (TextView) popupWindow
				.findViewById(R.id.tv_photo);
		popup_dismiss.setOnClickListener(this);
		popup_load.setOnClickListener(this);
		popup_camera.setOnClickListener(this);
	}
}
